package com.anlogic.sdk.tools.ui;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

import org.apache.logging.log4j.Logger;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.tm.terminal.view.core.TerminalServiceFactory;
import org.eclipse.tm.terminal.view.core.interfaces.ITerminalService;
import org.eclipse.tm.terminal.view.core.interfaces.constants.ITerminalsConnectorConstants;
import com.anlogic.sdk.utils.EnvUtils;
import com.anlogic.sdk.utils.LogUtils;

public class BspToolView extends CLIToolView {
	private static Logger logger = LogUtils.getLogger(BspToolView.class);
	
	private ITerminalService terminal;
	private Map<String, Object> terminalProperties;
	
	private final String VIEW_ID = "com.anlogic.sdk.tools.bspToolView";
	private final String VIEW_TITLE = "ASCT CLI";
	
	private ProcessController backendController;
	
	private static BspToolView instance;
	
	public BspToolView() {
		super();
		instance = this;
	}
	
    public static BspToolView getInstance() {
        return instance;
    }
    
    @Override
    public void createPartControl(Composite parent) {
    	super.createPartControl(parent);
    	terminal = TerminalServiceFactory.getService();
    	terminalProperties = newTerminalProperties();
    	openTerminal();
    }
    
    @Override
	public void dispose() {
    	closeTerminal();
    	super.dispose();
    }
    
	public Map<String, Object> newTerminalProperties() {
		Map<String, Object> properties = new HashMap<String, Object>();
		properties.put(ITerminalsConnectorConstants.PROP_ID, VIEW_ID);
		properties.put(ITerminalsConnectorConstants.PROP_TITLE, VIEW_TITLE);
		properties.put(ITerminalsConnectorConstants.PROP_ENCODING, StandardCharsets.UTF_8.name());
		properties.put(ITerminalsConnectorConstants.PROP_PROCESS_WORKING_DIR, ResourcesPlugin.getWorkspace().getRoot().getLocation().toString());
		properties.put(ITerminalsConnectorConstants.PROP_DELEGATE_ID,
				"org.eclipse.tm.terminal.connector.local.launcher.local");
		properties.put(ITerminalsConnectorConstants.PROP_TERMINAL_CONNECTOR_ID,
				"org.eclipse.tm.terminal.connector.local.LocalConnector");
		properties.put(ITerminalsConnectorConstants.PROP_PROCESS_PATH, EnvUtils.getIDEToolPath() + "/sw_cmd_tool" + EnvUtils.getCmdScriptExtend());
		properties.put(ITerminalsConnectorConstants.PROP_PROCESS_ARGS, "-i");
		return properties;
	}
	
	public void openTerminal() {
		// Create the done callback object
		ITerminalService.Done done = new ITerminalService.Done() {
			public void done(IStatus status) {
				// Place any post processing here
				startBackend();
			}
		};
		
		// Open the terminal
		if (terminal != null) {
			terminal.openConsole(terminalProperties, done);
		}
	}
	
	public void closeTerminal() {
		// Create the done callback object
		ITerminalService.Done done = new ITerminalService.Done() {
			public void done(IStatus done) {
				// Place any post processing here
				stopBackend();
			}
		};

		// Open the terminal
		if (terminal != null) {
			terminal.terminateConsole(terminalProperties, done);
			terminal.closeConsole(terminalProperties, done);
		}
	}
	
	public void startBackend() {
		if (backendController != null && backendController.isRunning()) {
			return;
		}
		Map<String, String> environment = System.getenv();
		File workDir = new File(ResourcesPlugin.getWorkspace().getRoot().getLocation().toOSString());
		String cmd1 = EnvUtils.getIDEToolPath() + "/asct/asct";
		String cmd2 = "-i2";
		backendController = new ProcessController();
		try {
			backendController.start(environment, workDir, cmd1, cmd2);
		} catch (IOException e) {
			logger.error("Start asct backend failed!");
		}
	}
	
	public void stopBackend() {
		try {
			backendController.stop();
		} catch (IOException e) {
			logger.error("Stop asct backend failed!");
		}
	}
	
	public ProcessController getBackend() {
		return backendController;
	}
}
